package py.com.alfa.escriba.gui.controller;

import java.io.Serializable;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.WebApplicationContext;
import org.thymeleaf.TemplateEngine;
import org.winter.dialect.response.JsonResponse;
import org.winter.utils.command.AjaxResponse;
import org.winter.utils.command.ControllerObject;

import py.com.alfa.escriba.gui.controller.object.gestion.TemplatesControllerObject;
import py.com.alfa.escriba.gui.controller.view.View;
import py.com.alfa.escriba.gui.controller.view.ViewManager;
import py.com.alfa.escriba.gui.dto.gestion.TemplatesDTO;
import py.com.alfa.escriba.gui.dto.gestion.VariablesDTO;
import py.com.alfa.escriba.gui.rest.services.TemplatesService;
import py.com.alfa.escriba.gui.rest.services.VariablesService;
import py.com.alfa.escriba.gui.services.HelperService;
import py.com.alfa.escriba.gui.services.TabRef;
import py.com.alfa.escriba.gui.session.SystemInfo;
import py.com.alfa.escriba.gui.spring.processors.SpringBean;
import py.com.sif.rest.client.spring.exception.RestClientException;

@Controller
@Scope("session")
@SessionAttributes("templates")
@RequestMapping("/templates")
public class TemplatesController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3176282958807625703L;
	private final static String PAGE_NAME = "pag:templates";
	private final static String CONTROLLER_OBJECT_NAME = "templates";
	
	private Logger log = LoggerFactory.getLogger(getClass());
	@SpringBean private TemplatesService templatesService;
	@SpringBean private VariablesService variablesService;
	@SpringBean private HelperService helperService;
	@SpringBean private SystemInfo systemInfo;
	@SpringBean private ViewManager viewManager;
	
	@Autowired
	private WebApplicationContext wac;
	
	@Autowired
	private TemplateEngine templateEngine;
	
	@ControllerObject
	private TemplatesControllerObject templates;	
	private Locale locale;
	
	public TemplatesController() {
		this.loadObjects();
	}

	private void loadObjects() {
		setLocale(LocaleContextHolder.getLocale());
	}

	private String verifAuto() {
		Subject subject = SecurityUtils.getSubject();
		if (subject == null || !subject.isAuthenticated()) {
			return "redirect:/";
		}		
		Boolean permitted = subject.isPermitted(TemplatesController.PAGE_NAME);
		systemInfo.setSystemError(false);
		if (!permitted) {
			systemInfo.setSystemError(true);
			systemInfo.setErrorMessage("El usuario no esta autorizado para utilizar este recurso");
			return "error";
		}
		return null;
	}
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String homePage(Model model, HttpServletRequest request, HttpServletResponse response) {
		this.log.debug("Templates!");
		try {
			this.getTemplates().view().disable().templates();
			String auto = this.verifAuto();
			if ( auto != null ) {
				return auto;
			}			
			this.getTemplates().setTemplates(this.templatesService.listTemplates());
			this.getTemplates().setTiposTemplate(this.helperService.getTablaRef(TabRef.TIPO_TEMPLATE));
			this.getTemplates().setTiposObjeto(this.helperService.getTablaRef(TabRef.TIPO_OBJETO));
			this.getTemplates().setVariables(this.variablesService.listVariables());
			this.getTemplates().view().enable().templates();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
		}
		return View.TEMPLATES;
	}
	
	@RequestMapping(value = "/crear", method = RequestMethod.POST)
	public @ResponseBody JsonResponse crear(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.TEMPLATES) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) TemplatesControllerObject templates, BindingResult bindingResult) {
		this.log.info("\n==============\nCREANDO!\n==============\n");
		try {
			this.log.info("\n==============\nTEMPLATES : {} - {}!\n==============\n",this.getTemplates().getTemplate());
			
			this.getTemplates().getTemplate().setIdescribano(systemInfo.getIdEscribano());
			this.templatesService.createTemplates(this.getTemplates().getTemplate());
			this.getTemplates().getTemplates().add(this.getTemplates().getTemplate());
			this.getTemplates().setTemplate(null);
			this.getTemplates().setTemplates(this.templatesService.listTemplates());
//			this.setTemplates(this.getTemplates());
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/nuevoTemplate", method = RequestMethod.POST)
	public @ResponseBody JsonResponse nuevoTemplate(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.TEMPLATES) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) TemplatesControllerObject templates, BindingResult bindingResult) {
		this.log.info("\n==============\nNUEVO!\n==============\n");
		try {
			this.getTemplates().setTemplate(new TemplatesDTO());
			this.getTemplates().view().enable().nuevo().disable().editar();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}

	@RequestMapping(value = "/eliminar/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse eliminar(Model model, HttpServletRequest request, HttpServletResponse response,
			 @PathVariable("index") String ind, @AjaxResponse(View.TEMPLATES) JsonResponse jResponse, 
			 @ModelAttribute(CONTROLLER_OBJECT_NAME) TemplatesControllerObject templates, BindingResult bindingResult) {
		try {
			Integer index = Integer.parseInt(ind);
			TemplatesDTO obj = this.getTemplates().getTemplates().get(index);
			this.log.info("TEMPLATE: {}", obj);
			
			this.templatesService.deleteTemplates(obj.getId());
            this.getTemplates().getTemplates().remove(obj);
            this.getTemplates().setTemplates(this.templatesService.listTemplates());
            this.getTemplates().view().enable().templates();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/editar/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse editar(Model model, HttpServletRequest request, HttpServletResponse response,
			 @PathVariable("index") String ind, @AjaxResponse(View.TEMPLATES) JsonResponse jResponse, 
			 @ModelAttribute(CONTROLLER_OBJECT_NAME) TemplatesControllerObject templates, BindingResult bindingResult) {
		this.log.info("\n==============\nEDITANDO! TEMPLATE\n==============\n");
		try {
			Integer index = Integer.parseInt(ind);
			TemplatesDTO obj = this.getTemplates().getTemplates().get(index);
			this.getTemplates().setTemplate(obj);
			this.getTemplates().view().disable().nuevo().enable().editar();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/actualizar", method = RequestMethod.POST)
	public @ResponseBody JsonResponse actualizar(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.TEMPLATES) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) TemplatesControllerObject templates, BindingResult bindingResult) {
		this.log.info("\n==============\nEDITANDO TEMPLATES!\n==============\n");
		try {
			this.log.info("\n==============\nTEMPLATES: {}!\n==============\n", this.getTemplates().getTemplate());
			this.templatesService.saveTemplates(this.getTemplates().getTemplate());
			this.getTemplates().setTemplate(null);
			this.getTemplates().view().disable().nuevo().disable().editar();
			this.getTemplates().setTemplates(this.templatesService.listTemplates());
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/cancelar", method = RequestMethod.POST)
	public @ResponseBody JsonResponse cancelar(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.TEMPLATES) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) TemplatesControllerObject templates, BindingResult bindingResult) {
		this.log.info("\n==============\nCancelar!\n==============\n");
		try {
			this.getTemplates().setTemplate(null);
			this.getTemplates().setTemplates(this.templatesService.listTemplates());
			this.getTemplates().view().templates().enable();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/selectVariable/{id}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse selectVariable(Model model, HttpServletRequest request, HttpServletResponse response,
			 @PathVariable("id") String id, @AjaxResponse(View.TEMPLATES) JsonResponse jResponse, 
			 @ModelAttribute(CONTROLLER_OBJECT_NAME) TemplatesControllerObject templates, BindingResult bindingResult) {
		try {
			Long idVariable = Long.parseLong(id);
			VariablesDTO obj = new VariablesDTO(idVariable);
			Integer index = this.getTemplates().getVariables().indexOf(obj);
			obj = this.getTemplates().getVariables().get(index);
			this.log.info("VARIABLE: {}", obj);
			
			TemplatesDTO template = this.getTemplates().getTemplate();
			
			this.log.info("\n==================\nTEXT BEFORE: {}\n==================\n", template.getTexto());
			
			if(template.getTexto() == null)
				template.setTexto(new String());
			
			StringBuffer sb = new StringBuffer(template.getTexto());
			sb.append("{{").append(obj.getNombre()).append("}}");
			template.setTexto(sb.toString());
			
			this.log.info("\n==================\nTEXT AFTER: {}\n==================\n", template.getTexto());
			
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}

	
	@ModelAttribute(CONTROLLER_OBJECT_NAME)
	public TemplatesControllerObject getTemplates() {
		return this.templates;
	}
	
	public void setTemplates(TemplatesControllerObject templates) {
		this.templates = templates;
	}

	public Locale getLocale() {
		return locale;
	}

	public void setLocale(Locale locale) {
		this.locale = locale;
	}	
}
